<?php
/**
 * Created by PhpStorm.
 * User: xkq
 * Date: 2017/8/9 0009
 * Time: 22:22
 */
set_include_path(dirname(dirname(__FILE__)));
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') == false) {
    echo '<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/></head> <body>请在微信中打开！！！</body></html>';
    exit;
}
include_once("inc/init.php");
include 'function.php';
session_start();
global $smarty;
$userid = $_COOKIE['userid'];
if(empty($userid)){
    $smarty->display('login.htm');
    exit;
}
$action = crequest("action");
$action = $action == '' ? 'index' : $action;

switch ($action)
{
    case "index":
        index();
        break;
    case "share":
        share();
        break;
    case "redpack":
        redpack();
        break;
    case "order":
        order();
        break;
    case "paysuc":
        paysuc();
        break;
    case "record":
        record();
        break;
    case "detail":
        detail();
        break;
    case "panel_list":
        panel_list();
        break;
    case "logout":
        logout();
        break;

}

//首页
function index(){
    global $db, $smarty;
    $userid = $_COOKIE['userid'];
    $sql = "SELECT * FROM user WHERE userid = $userid";
    $user = $db->get_row($sql);
    if(!$user['openid']) {
        $url = INDEX_URL;
        $code = getCode($url);
        $access_token = getOpenId($code);
        $userInfo = getUserInfo($access_token);
        if($userInfo && !empty($userInfo)) {
            $data['nickname'] = $userInfo['nickname'];
            $data['gender'] = $userInfo['sex'];
            $data['openid'] = $userInfo['openid'];
            $data['avatar'] = $userInfo['headimgurl'];
            $data['unionid'] = $userInfo['unionid'];
            $db->update('user', $data, "userid = $userid");
        } else {
            href_locate(INDEX_URL);
        }
    }
    $sql = "SELECT * FROM user WHERE userid = $userid";
    $user = $db->get_row($sql);
    $smarty->assign('user', $user);
    $smarty->display('index.htm');

}

function share(){
    global $db, $smarty;
    $smarty->assign('userid', irequest("userid"));
    $smarty->assign('signPackage', getSignPackage());
    $smarty->display('share.htm');
}

function redpack(){
    global $db, $smarty;
    $smarty->assign('userid', irequest("userid"));
    $smarty->assign('signPackage', getSignPackage());
    $smarty->display('redpack.htm');
}

function paysuc(){
    global $db, $smarty;
    $smarty->assign('ordersn', $_GET['ordersn']);
    $smarty->assign('signPackage', getSignPackage());
    $smarty->display('paysuc.htm');
}

function record(){
    global $db, $smarty;
    $userid = $_GET['userid'];
    $sql = "SELECT * FROM `order` WHERE userid='{$userid}' and status = 2  ORDER BY id DESC";
    $orderinfo = $db->get_all($sql);
    foreach($orderinfo as $key=>$val){
        if($val['use_status'] == 0){
            $orderinfo[$key]['use'] = "待领取";
        }else{
            $orderinfo[$key]['use'] = "已领取";
        }
        $orderinfo[$key]['cost'] = $val['cost'];
    }
    $smarty->assign('orderinfo', $orderinfo);
    $smarty->assign('signPackage', getSignPackage());
    $smarty->display('record.htm');
}

function detail(){
    global $db, $smarty;
    $odersn = crequest("ordersn");
    $sql = "SELECT * FROM `user_dingwei` WHERE ordersn='{$odersn}' and type = 2";
    $orderinfo = $db->get_row($sql);
    $smarty->assign('orderinfo', $orderinfo);
    $smarty->display('detail.htm');
}

function panel_list(){
    global $db, $smarty;
    $userid = crequest("userid");
    $sql = "SELECT * FROM `user_dingwei` WHERE sid='{$userid}' and type = 1 ORDER BY userid DESC";
    $orderinfo = $db->get_all($sql);
    $smarty->assign('orderinfo', $orderinfo);
    $smarty->display('panel_list.htm');
}

function logout(){
    setcookie("userid", "" , time()-1);
    unset($_COOKIE['userid']);
    alert_back('退出成功！！');
}


function order(){
    global $db,$smarty;;
    $userid = isset($_POST['userid']) ? trim($_POST['userid']) : alert_back('userid_error');
    $sql = "SELECT * FROM user WHERE userid='{$userid}'";
    $userinfo = $db->get_row($sql);
    if(!$userinfo){
        alert_back('user_not_find');
    }
    $info=array();
    $openid = $userinfo['openid'];

    if (empty($openid)){
        alert_back('openid获取失败');
    }
    if(!empty($_POST['cost'])) {
        $info['userid'] = $userid;
        $info['mobile'] = $userinfo['mobile'];
        $info['username'] = $userinfo['username'];
        $info['cost'] = $_POST['cost'];

        //测试用户数组
//        $test_user = [
//            'oEvcj0TtmllEYWaqDVl94QUkQcbE',
//            'oEvcj0V-hP_46UZPw4h9KqKL2gEc',
//            'oEvcj0UMln0vs2TF1_BYD6vjKuHw',
//            'oEvcj0W6eFyJVmajahm6ISIw5MLo',
//            'oEvcj0bWytRRgvsUc1aYYUe1g9Z8',
//            'oEvcj0RzINEiKUZU_6R5FbcJ3NyQ',
//            'oEvcj0arK4Q3RggH0R7fVhOW2qGE',
//            'oEvcj0UuB34csXQsfp9M1ePFcT3s',
//            'oEvcj0Ym_USgkJirRfJQpHAEcFY8',
//        ];

        //如果在测试用户中，则订单价格为0.01
//        if (in_array($userinfo['openid'], $test_user)) {
//            $cost = '0.01';
//        }
        $info['ordersn'] = date('Ymd') . substr(microtime(), 2, 3) . rand(1000, 9999);
        $info['add_time'] = time();
        $info['add_time_format'] = now_time();
        $info['status'] = 1;
        $db->insert('order', $info);
        $sql = "SELECT * FROM `order` WHERE ordersn='{$info['ordersn']}'";
        $orderinfo = $db->get_row($sql);
        if (!$orderinfo) {
            alert_back('order_insert_error');
        }
        $orderinfo['openid'] = $openid;
        //   $orderinfo['formid'] = $_POST['formid'];
        $jsApiParameters = wx_pay($orderinfo);
//        $json = json_decode($jsApiParameters,true);
//        $_COOKIE['json'] =  $json;

//        $sql = "UPDATE `order` SET `prepay_id` = '{$json['prepay_id']}' WHERE  ordersn='{$orderinfo['ordersn']}'";
//        print_r($sql);
//        $db->query($sql);

        $smarty->assign('orderinfo', $orderinfo);
        $smarty->assign('userid', $userid);
        $smarty->assign('jsApiParameters', $jsApiParameters);
        $smarty->display('order.htm');
    }else{
        alert_back('cost_error');
    }
}

function wx_pay($orderinfo){
    ini_set('date.timezone','Asia/Shanghai');
//error_reporting(E_ERROR);
    require_once "weixin/lib/WxPay.Api.php";
    require_once "weixin/example/WxPay.JsApiPay.php";
    require_once 'weixin/example/log.php';

//初始化日志
//    $logHandler= new CLogFileHandler("weixin/logs/".date('Y-m-d').'.log');
//    $log = Log::Init($logHandler, 15);


//①、获取用户openid
    $tools = new JsApiPay();
   // $openId = $tools->GetOpenid();
    $openId = $orderinfo['openid'];
    $cost = intval($orderinfo['cost']*100);   //微信金额以分为单位

//②、统一下单
    $input = new WxPayUnifiedOrder();
    $input->SetBody("未来动力科技定位红包");
    $input->SetAttach("未来动力科技");
    $input->SetOut_trade_no($orderinfo['ordersn']);
    $input->SetTotal_fee($cost);
    $input->SetTime_start(date("YmdHis"));
    $input->SetTime_expire(date("YmdHis", time() + 600));
    $input->SetGoods_tag("未来动力科技订单");
    $input->SetNotify_url(WE_NOTIFY_URL);
    $input->SetTrade_type("JSAPI");
    $input->SetOpenid($openId);
    $order = WxPayApi::unifiedOrder($input);
//    echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
//    foreach($order as $key=>$value){
//        echo "<font color='#00ff55;'>$key</font> : $value <br/>";
//    }
    $jsApiParameters = $tools->GetJsApiParameters($order);
    return $jsApiParameters;
}
